package com.asdc.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 手写一个轮询算法：
 * <p>
 * rest 访问第几次 % 集群主机数 = 对应主机下标index
 * serviceInstances.get(index) 就是那台主机
 */
@Component
public class MyLB implements MyLoadBalance {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    // CAS
    public int getCurrentAndIncreasment() {
        int curr;
        int next;
        do {
            curr = atomicInteger.get();
            next = curr > Integer.MAX_VALUE ? 0 : curr + 1;
        } while (!atomicInteger.compareAndSet(curr, next));
        System.out.println("第【" + next + "】次访问");
        return next;
    }

    @Override
    public ServiceInstance servinceInstence(List<ServiceInstance> serviceInstances) {
        int index = this.getCurrentAndIncreasment() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
